<script setup lang="tsx">
import { computed, nextTick, ref, unref, watch } from 'vue'
import { useDesign } from '@sat/shared-hooks'
import {
  ElInput,
  ElPagination,
  ElPopover,
  ElScrollbar,
  ElTabPane,
  ElTabs,
} from 'element-plus'
import type { CSSProperties } from 'vue'
import { Icon } from '../../Icon'

const props = withDefaults(
  defineProps<{
    size: 'small' | 'default' | 'large'
  }>(),
  {
    size: 'default',
  },
)

const iconSetData = import.meta.glob<{
  name: string
  prefix: string
  icons: string[]
}>('./data/icons.*.ts', {
  import: 'default',
  eager: true,
})

const icons = Object.values(iconSetData)

const modelValue = defineModel<string>()

const iconSize = computed(() => {
  return props.size === 'small'
    ? 'var(--el-component-size-small)'
    : props.size === 'large'
      ? 'var(--el-component-size-large)'
      : 'var(--el-component-size)'
})

const iconWrapStyle = computed((): CSSProperties => {
  return {
    width: '100px',
    height: iconSize.value,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow:
      '0 0 0 1px var(--el-input-border-color,var(--el-border-color)) inset',
    position: 'relative',
    left: '-1px',
    cursor: 'pointer',
  }
})

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('icon-picker')

const iconName = ref(icons[0].prefix)

const pageSize = ref(54)

const currentPage = ref(1)

const keywords = ref('')

const currentIconNameIndex = computed(() => {
  const index = icons.findIndex(item => item.prefix === iconName.value)
  return index
})

const currentIcons = computed(() => {
  return icons[currentIconNameIndex.value]?.icons
})

const filterIcons = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = currentPage.value * pageSize.value
  let res = currentIcons.value
  if (keywords.value)
    res = res?.filter(item => item.includes(keywords.value))

  return res?.slice(start, end)
})

function tabChange() {
  currentPage.value = 1
}

watch(
  () => modelValue.value,
  (val) => {
    init(val)
  },
  {
    immediate: true,
  },
)

async function init(icon?: string) {
  if (!icon)
    return
  const iconInfo = icon.split(':')
  iconName.value = iconInfo[0]
  const wrapIndex = icons.findIndex(item => item.prefix === iconInfo[0])
  // 查询当前icon的索引
  const index = icons[wrapIndex]?.icons?.findIndex(item => item === icon)
  // 计算当前icon的页码
  await nextTick()
  currentPage.value = Math.ceil((index + 1) / pageSize.value)
}

function popoverShow() {
  init(unref(modelValue))
}

function iconSelect(icon: string) {
  modelValue.value = icon
}
</script>

<template>
  <div :class="prefixCls" class="box flex items-center justify-center">
    <ElInput v-model="modelValue" />
    <ElPopover
      placement="bottom"
      trigger="click"
      :width="450"
      popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; height: 440px;"
      @show="popoverShow"
    >
      <template #reference>
        <div :style="iconWrapStyle">
          <Icon v-if="modelValue" :icon="modelValue" />
          <span v-else>选择图标</span>
        </div>
      </template>
      <ElInput v-model="keywords" placeholder="输入关键字检索当前图表集" />
      <ElScrollbar class="h-[calc(100%-90px)]!">
        <ElTabs v-model="iconName" tab-position="left" @tab-change="tabChange">
          <ElTabPane
            v-for="item in icons"
            :key="item.name"
            :label="item.name"
            :name="item.prefix"
          >
            <div class="box-border flex flex-wrap">
              <div
                v-for="icon in filterIcons"
                :key="icon"
                :style="{
                  width: iconSize,
                  height: iconSize,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                  border: `1px solid ${
                    icon === modelValue
                      ? 'var(--el-color-primary)'
                      : 'var(--el-border-color)'
                  }`,
                  boxSizing: 'border-box',
                  margin: '2px',
                }"
                @click="iconSelect(icon)"
              >
                <Icon
                  :icon="icon"
                  :color="
                    icon === modelValue ? 'var(--el-color-primary)' : 'inherit'
                  "
                />
              </div>
            </div>
          </ElTabPane>
        </ElTabs>
      </ElScrollbar>
      <div
        class="absolute bottom-0 left-0 h-50px w-100% flex items-center justify-center pl-[var(--el-popover-padding)] pr-[var(--el-popover-padding)]"
      >
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :pager-count="5"
          small
          layout="total, prev, pager, next, jumper"
          :total="icons[currentIconNameIndex]?.icons?.length || 0"
        />
      </div>
    </ElPopover>
  </div>
</template>

<style lang="less" scoped>
@prefix-cls: ~'@{namespace}-icon-picker';

.@{prefix-cls} {
  :deep(.@{elNamespace}-input__wrapper) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
}
</style>
